package com.study.task;

import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * 动态修改cron参数
 */
@Component
@EnableScheduling
@RequestMapping("/task")
public class TaskCronChange implements InitializingBean, SchedulingConfigurer {

    /**
     * 执行周期
     */
    private String cron;

    /**
     * 1.初始化参数, 换成构造方法也行
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //初始时一秒一次
        cron = "0 1 1 1 * ?";
        System.out.println("初始化完成：" + cron);
    }

    /**
     * 2.初始化定时任务配置
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(taskRun, trigger);
    }

    /**
     * 3.定时任务逻辑
     */
    Thread taskRun = new Thread(()-> {
        System.out.println("任务逻辑执行中，当前时间：" + DateUtil.now());
    });

    /**
     * 4.Trigger修改定时任务的执行周期
     */
    Trigger trigger = new Trigger() {
        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExecutionTime = trigger.nextExecutionTime(triggerContext);
            return nextExecutionTime;
        }
    };

    /**
     * 5.外部修改cron
     * http://127.0.0.1:8887/study/task/changeCron?cron=0/5 * * * * ?
     */
    @GetMapping(value = "/changeCron")
    @ResponseBody
    public String changeCron(@RequestParam("cron") String cron) throws Exception {
        this.cron = cron;
        System.out.println("模拟外部更改完成：" + cron);
        return "修改成功";
    }
}
